package org.loong.crypto.service.software.provider.asymmetric.ecdsa;

import java.security.interfaces.ECPublicKey;

import org.loong.crypto.common.exception.CryptoException;
import org.loong.crypto.common.exception.InvalidKeyException;
import org.loong.crypto.core.algorithm.SignatureAlgorithm;
import org.loong.crypto.core.utils.ECKeyUtils;
import org.loong.crypto.service.core.provider.Verifier;
import org.loong.crypto.service.core.provider.impl.ECDSAProvider;

import cn.hutool.crypto.asymmetric.Sign;

/**
 * ECDSA verifier of signature.
 */
public class ECDSAVerifier extends ECDSAProvider implements Verifier {

    /**
     * The public key.
     */
    private ECPublicKey publicKey;

    /**
     * Creates a new verifier.
     *
     * @param keyBytes the public key bytes. Must not be {@code null}.
     */
    public ECDSAVerifier(final byte[] keyBytes) {
        this(ECKeyUtils.toECPublicKey(keyBytes));
    }

    /**
     * Creates a new verifier.
     *
     * @param publicKey the public key. Must not be {@code null}.
     */
    public ECDSAVerifier(final ECPublicKey publicKey) {
        if (publicKey == null) {
            throw new InvalidKeyException("The public ECDSA key must not be null.");
        }

        if (!"EC".equalsIgnoreCase(publicKey.getAlgorithm())) {
            throw new InvalidKeyException("The public key algorithm must be ECDSA.");
        }

        this.publicKey = publicKey;
    }

    @Override
    public boolean verify(final SignatureAlgorithm algorithm, final byte[] data, final byte[] signature) throws CryptoException {
        try {
            Sign verifier = new Sign(algorithm.getName(), null, publicKey);
            return verifier.verify(data, signature);
        } catch (cn.hutool.crypto.CryptoException e) {
            return false;
        }
    }
}
